package com.ming.learn.from.carl.binary.tree;

import com.ming.commons.utils.TreeNode;
import com.sun.jmx.remote.internal.ArrayQueue;

/*
104.二叉树的最大深度
 */
public class Of20210307LeetCode104 {
    /*
    二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
     */
    public static void main(String[] args) {
        System.out.println(maxDepth2(new TreeNode(1, new TreeNode(2, new TreeNode(3, new TreeNode(2), null), new TreeNode(4)),
                null)));
    }

    /*
    递归法
     */
    private static int maxDepth(TreeNode root) {
        if (root == null) return 0;
        return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
    }

    /*
    迭代法
     */
    private static int maxDepth2(TreeNode root) {
        if (root == null) return 0;
        int maxDepth = 0;
        ArrayQueue<TreeNode> queue = new ArrayQueue<TreeNode>(10);
        queue.add(root);
        while (!queue.isEmpty()) {
            for (int i = 0; i < queue.size(); i++) {
                TreeNode node = queue.remove(0);
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
            maxDepth++;
        }

        return maxDepth;
    }

}
